<?php

namespace app\admin\command;

use Carbon\Carbon;
use fast\Random;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\DutyList as DutyModel;
use app\admin\model\pt\Salary as SalaryModel;
use app\admin\model\pt\Statistic as StatisticModel;
use app\admin\model\pt\StatisticaDepart as StatisticaDepartModel;
use app\admin\model\pt\StatisticaDay as StatisticaDayModel;

class Statistic extends Command
{

    // 在CalPersonSalary后运行
    protected function configure()
    {
        $defaultDateId = date('Ymd', strtotime('-1 day'));
        $this->setName('statistic')
            ->addOption('date', 'd', Option::VALUE_OPTIONAL, 'date', $defaultDateId)
            ->setDescription('statistic   零点并在所有脚本后运行');
    }
    
    protected function execute(Input $input, Output $output)
    {
        @ini_set("memory_limit",'-1');
        $stime=microtime(true);

        $curDate = $input->getOption('date');
        $curMonth = date('Ym', strtotime($curDate));

        $logPre = 'statistic ';
        Log::write($logPre . ': 统计前一天数据开始, date =>' . $curDate);
        Log::write($logPre . ': 统计部门每日数据开始, date =>' . $curDate);
        // 先计算每天各部门的人次和费用
        $allDeparts = DepartModel::where('id', '>', '0')->select();
        foreach ($allDeparts as $depart) {
            Db::startTrans();
            try {
                $consumeTotalFee = Db::name('pt_person_salary')->where('pt_depart_id', $depart->id)
                                                        ->where('salary_total', '>', 0)
                                                        ->where('date_id',  $curDate)
                                                        ->sum('salary_total');
                // 计算已消耗人次
                $consumeTotalPersons = Db::name('pt_duty_list')->where('pt_depart_id', $depart->id)
                                                        ->where('date_id', $curDate)
                                                        ->count('id');

                $dayModel = StatisticaDayModel::where('pt_depart_id', $depart->id)
                  ->where('month_id', $curMonth)
                  ->where('date_id', $curDate)
                  ->find();
                $params = [];
                $params['fee_total'] = $consumeTotalFee;
                $params['person_total'] = $consumeTotalPersons;
                if (!$dayModel) {
                    $dayModel = new StatisticaDayModel();
                    $params['pt_depart_id'] = $depart->id;
                    $params['month_id'] = $curMonth;
                    $params['date_id'] = $curDate;
                } else {
                    $params['id'] = $dayModel->id;
                }
                $dayModel->save($params);
                Db::commit();
                Log::write($logPre . ': 统计部门每天费用和人次结束, date =>' . $curDate . ', depart id =>'. $depart->id);
            } catch (Exception $e) {
                Db::rollback();
                print_r($e->getTraceAsString());
                Log::write($logPre . ': 统计部门每天费用和人次失败, message:'.$e->getTraceAsString() .', date =>' . $curDate . ', depart id =>'. $depart->id);
            }
        }
        Log::write($logPre . ': 统计部门每日数据结束, date =>' . $curDate);
        
        Log::write($logPre . ': 统计部门每月数据开始, date =>' . $curMonth);
        // 统计到部门的按月记录表
        $allDeparts = DepartModel::where('id', '>', '0')->select();
        foreach ($allDeparts as $depart) {
            Db::startTrans();
            try {
                $consumeTotalFee = Db::name('pt_statistica_day')->where('pt_depart_id', $depart->id)
                                                        ->where('month_id',  $curMonth)
                                                        ->sum('fee_total');
                // 计算已消耗人次
                $consumeTotalPersons = Db::name('pt_statistica_day')->where('pt_depart_id', $depart->id)
                                                        ->where('month_id', $curMonth)
                                                        ->sum('person_total');

                $staDepartModel = StatisticaDepartModel::where('pt_depart_id', $depart->id)
                  ->where('month_id', $curMonth)
                  ->find();
                $params = [];
                $params['fee_total'] = $consumeTotalFee;
                $params['person_total'] = $consumeTotalPersons;
                if (!$staDepartModel) {
                    $staDepartModel = new StatisticaDepartModel();
                    $params['pt_depart_id'] = $depart->id;
                    $params['month_id'] = $curMonth;
                } else {
                    $params['id'] = $staDepartModel->id;
                }
                $staDepartModel->save($params);
                Db::commit();
                Log::write($logPre . ': 统计部门每月费用和人次结束, date =>' . $curMonth . ', depart id =>'. $depart->id);
            } catch (Exception $e) {
                Db::rollback();
                print_r($e->getTraceAsString());
                Log::write($logPre . ': 统计部门每月费用和人次失败, message:'.$e->getTraceAsString() .', date =>' . $curMonth . ', depart id =>'. $depart->id);
            }
        }
        Log::write($logPre . ': 统计部门每月数据结束, date =>' . $curMonth);
        // 统计公司每月数据
        Log::write($logPre . ': 统计公司每月数据开始, date =>' . $curMonth);
        Db::startTrans();
        try {
            $consumeTotalFee = Db::name('pt_statistica_depart')
                                                    ->where('month_id',  $curMonth)
                                                    ->sum('fee_total');
            $consumeTotalPersons = Db::name('pt_statistica_depart')
                                                    ->where('month_id', $curMonth)
                                                    ->sum('person_total');

            $staModel = StatisticModel::where('month_id', $curMonth)
              ->find();
            $params = [];
            $params['fee_total'] = $consumeTotalFee;
            $params['person_total'] = $consumeTotalPersons;
            if (!$staModel) {
                $staModel = new StatisticModel();
                $params['month_id'] = $curMonth;
            } else {
                $params['id'] = $staModel->id;
            }
            $staModel->save($params);
            Db::commit();
            Log::write($logPre . ': 统计公司每月费用和人次结束, date =>' . $curMonth);
        } catch (Exception $e) {
            Db::rollback();
            print_r($e->getTraceAsString());
            Log::write($logPre . ': 统计公司每月费用和人次失败, message:'.$e->getTraceAsString() .', date =>' . $curMonth);
        }

        Log::write($logPre . ': 统计公司每月数据结束, date =>' . $curMonth);
        
        
        $etime=microtime(true);//获取程序执行结束的时间
        $total=$etime-$stime;   //计算差值
        $output->writeln($total);
        $output->info('statistic success');
    }
    

}
